import { user, system } from '@/store';
import systemConfig from '@/common/config';
import { encryptSM2 } from '@/common/utils/util';
import { SM3 } from 'gm-crypto';

export function signatureGenerate(config: any) {
  // 密钥，可以是前后端约定好的某一串，也可以是随机的，动态的。
  let data = config.data;
  if (typeof data === 'string') {
    data = JSON.parse(data);
  }
  let params = config.params;
  if (typeof params === 'string') {
    params = JSON.parse(params);
  }
  if (systemConfig.cryptoEnabled && (system.allApiCrytpo || config?.header?.cryptoEnabled === 'true'|| config?.header?.cryptoEnabled === true)) {
    let secretKey = '';
    if (data && !('cryptoStr' in data)) {
      data = { cryptoStr: encryptSM2(JSON.stringify(data), secretKey) };
      config.data = data;
    }
    if (params&&params.length && !('cryptoStr' in params)) {
      params = { cryptoStr: encryptSM2(JSON.stringify(params), secretKey) };
      config.params = params;
    }
  }
  let secret = '' as string | null | undefined;
  const token = user.accesstoken;
  if (token) {
    secret = user.defaultSM2PrivateKey;
  } else {
    secret = system.defaultSM2PrivateKey;
  }
  // 时间戳
  let timestamp = new Date().getTime();
  // post参数
  let dataStr = '';
  if (params) {
    if (params.length) {
      let sortParams = sortAescParams(params);
      config.params = sortParams;
      dataStr = JSON.stringify(sortParams);
    }
  }
  if (data) {
    dataStr = dataStr + JSON.stringify(sortAesc(data));
  }

  // 生成签名
  let str = dataStr + '&secret=' + secret + '&timestamp=' + timestamp;
  console.log('前端签名完整内容：' + str);
  const sign = systemConfig.signEnabled ? SM3.digest(str, 'utf8', 'hex') : '';
  console.log('前端签名后：' + sign.toUpperCase());
  const dataSign = SM3.digest(config.url + dataStr, 'utf8', 'hex');
  return {
    signature: systemConfig.signEnabled ? sign.toUpperCase() : '', // 将签名字母转为大写
    timestamp,
    dataSign: dataSign,
  };
}
export function signFileParams(){
  //文件签名，只用应用秘钥进行签名
  let secret = '' as string | null | undefined;
  secret = system.defaultSM2PrivateKey;
  // 时间戳
  let timestamp = new Date().getTime();
  let appId=systemConfig.appId
  // 生成签名
  let str ='appId=' + appId+'&secret=' + secret + '&timestamp=' + timestamp;
  console.log('前端签名完整内容：' + str);
  const sign = systemConfig.signEnabled ? SM3.digest(str, 'utf8', 'hex') : '';
  console.log('前端签名后：' + sign.toUpperCase());
  return {
    signature: systemConfig.signEnabled ? sign.toUpperCase() : '', // 将签名字母转为大写
    timestamp,
    appId
  };
}
export function getFileSignParams(){
  const {signature, timestamp,appId} =signFileParams();
  let str='?signature='+signature+'&timestamp='+timestamp+"&appId="+appId;
  if(user.accesstoken){
    str=str+"&accessToken="+user.accesstoken;
  }
  return str;
}
//复杂json的key排序
const sortAesc = (obj: any) => {
  const sortObj = {} as any;
  Object.keys(obj)
    .sort()
    .forEach((item) => {
      let itemOjb = obj[item];
      if (itemOjb != null && itemOjb != undefined) {
        if (itemOjb instanceof Array) {
          let arrChild = [] as any;
          itemOjb.forEach((index: any) => {
            if (index.constructor === Object) {
              let Objarr = sortAesc(index);
              arrChild.push(Objarr);
            } else {
              arrChild.push(index);
            }
          });
          sortObj[item] = arrChild;
        } else if (itemOjb.constructor === Object) {
          if (itemOjb != null && itemOjb != undefined) {
            sortObj[item] = sortAesc(itemOjb);
          }
        } else {
          sortObj[item] = itemOjb;
        }
      }
    });
  return sortObj;
};
const sortAescParams = (obj: any) => {
  const sortObj = {} as any;
  Object.keys(obj)
    .sort()
    .forEach((item) => {
      let itemOjb = obj[item];
      if (itemOjb != null && itemOjb != undefined) {
        if (typeof itemOjb == 'string') {
          sortObj[item] = itemOjb;
        } else {
          sortObj[item] = JSON.stringify(itemOjb);
        }
      }
    });
  return sortObj;
};
